* (bug 1735) Revamped protection interface
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @package MediaWiki
5 */
6
7 /**
8 * Need the CacheManager to be loaded
9 */
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
12
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
15
16 /**
17 * Class representing a MediaWiki article and history.
18 *
19 * See design.txt for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
22 *
23 * @package MediaWiki
24 */
25 class Article {
26 /**#@+
27 * @access private
28 */
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mGoodAdjustment, $mTotalAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
34 var $mId, $mTable;
35 var $mForUpdate;
36 var $mOldId;
37 var $mRevIdFetched;
38 var $mRevision;
39 /**#@-*/
40
41 /**
42 * Constructor and clear the article
43 * @param mixed &$title
44 */
45 function Article( &$title ) {
46 $this->mTitle =& $title;
47 $this->clear();
48 }
49
50 /**
51 * get the title object of the article
52 * @public
53 */
54 function getTitle() {
55 return $this->mTitle;
56 }
57
58 /**
59 * Clear the object
60 * @private
61 */
62 function clear() {
63 $this->mDataLoaded = false;
64 $this->mContentLoaded = false;
65
66 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
67 $this->mRedirectedFrom = $this->mUserText =
68 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
69 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
70 $this->mTouched = '19700101000000';
71 $this->mForUpdate = false;
72 $this->mIsRedirect = false;
73 $this->mRevIdFetched = 0;
74 }
75
76 /**
77 * Note that getContent/loadContent may follow redirects if
78 * not told otherwise, and so may cause a change to mTitle.
79 *
80 * @param $noredir
81 * @return Return the text of this revision
82 */
83 function getContent( $noredir ) {
84 global $wgRequest, $wgUser, $wgOut;
85
86 # Get variables from query string :P
87 $action = $wgRequest->getText( 'action', 'view' );
88 $section = $wgRequest->getText( 'section' );
89 $preload = $wgRequest->getText( 'preload' );
90
91 $fname = 'Article::getContent';
92 wfProfileIn( $fname );
93
94 if ( 0 == $this->getID() ) {
95 if ( 'edit' == $action ) {
96 wfProfileOut( $fname );
97
98 # If requested, preload some text.
99 $text=$this->getPreloadedText($preload);
100
101 # We used to put MediaWiki:Newarticletext here if
102 # $text was empty at this point.
103 # This is now shown above the edit box instead.
104 return $text;
105 }
106 wfProfileOut( $fname );
107 $wgOut->setRobotpolicy( 'noindex,nofollow' );
108
109 $ret = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
110 return "<div class='noarticletext'>$ret</div>";
111 } else {
112 $this->loadContent( $noredir );
113 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
114 if ( $this->mTitle->getNamespace() == NS_USER_TALK &&
115 $wgUser->isIP($this->mTitle->getText()) &&
116 $action=='view'
117 ) {
118 wfProfileOut( $fname );
119 return $this->mContent . "\n" .wfMsg('anontalkpagetext');
120 } else {
121 if($action=='edit') {
122 if($section!='') {
123 if($section=='new') {
124 wfProfileOut( $fname );
125 $text=$this->getPreloadedText($preload);
126 return $text;
127 }
128
129 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
130 # comments to be stripped as well)
131 $rv=$this->getSection($this->mContent,$section);
132 wfProfileOut( $fname );
133 return $rv;
134 }
135 }
136 wfProfileOut( $fname );
137 return $this->mContent;
138 }
139 }
140 }
141
142 /**
143 This function accepts a title string as parameter
144 ($preload). If this string is non-empty, it attempts
145 to fetch the current revision text. It respects
146 <includeonly>.
147 */
148 function getPreloadedText($preload) {
149 if($preload) {
150 $preloadTitle=Title::newFromText($preload);
151 if(isset($preloadTitle) && $preloadTitle->userCanRead()) {
152 $rev=Revision::newFromTitle($preloadTitle);
153 if($rev) {
154 $text=$rev->getText();
155 $text=preg_replace('/<\/?includeonly>/i','',$text);
156 return $text;
157 }
158 }
159 }
160 return '';
161 }
162
163 /**
164 * This function returns the text of a section, specified by a number ($section).
165 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
166 * the first section before any such heading (section 0).
167 *
168 * If a section contains subsections, these are also returned.
169 *
170 * @param string $text text to look in
171 * @param integer $section section number
172 * @return string text of the requested section
173 */
174 function getSection($text,$section) {
175
176 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
177 # comments to be stripped as well)
178 $striparray=array();
179 $parser=new Parser();
180 $parser->mOutputType=OT_WIKI;
181 $parser->mOptions = new ParserOptions();
182 $striptext=$parser->strip($text, $striparray, true);
183
184 # now that we can be sure that no pseudo-sections are in the source,
185 # split it up by section
186 $secs =
187 preg_split(
188 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
189 $striptext, -1,
190 PREG_SPLIT_DELIM_CAPTURE);
191 if($section==0) {
192 $rv=$secs[0];
193 } else {
194 $headline=$secs[$section*2-1];
195 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
196 $hlevel=$matches[1];
197
198 # translate wiki heading into level
199 if(strpos($hlevel,'=')!==false) {
200 $hlevel=strlen($hlevel);
201 }
202
203 $rv=$headline. $secs[$section*2];
204 $count=$section+1;
205
206 $break=false;
207 while(!empty($secs[$count*2-1]) && !$break) {
208
209 $subheadline=$secs[$count*2-1];
210 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
211 $subhlevel=$matches[1];
212 if(strpos($subhlevel,'=')!==false) {
213 $subhlevel=strlen($subhlevel);
214 }
215 if($subhlevel > $hlevel) {
216 $rv.=$subheadline.$secs[$count*2];
217 }
218 if($subhlevel <= $hlevel) {
219 $break=true;
220 }
221 $count++;
222
223 }
224 }
225 # reinsert stripped tags
226 $rv=$parser->unstrip($rv,$striparray);
227 $rv=$parser->unstripNoWiki($rv,$striparray);
228 $rv=trim($rv);
229 return $rv;
230
231 }
232
233 /**
234 * Return the oldid of the article that is to be shown.
235 * For requests with a "direction", this is not the oldid of the
236 * query
237 */
238 function getOldID() {
239 global $wgRequest, $wgOut;
240 static $lastid;
241
242 if ( isset( $lastid ) ) {
243 return $lastid;
244 }
245 # Query variables :P
246 $oldid = $wgRequest->getVal( 'oldid' );
247 if ( isset( $oldid ) ) {
248 $oldid = intval( $oldid );
249 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
250 $nextid = $this->mTitle->getNextRevisionID( $oldid );
251 if ( $nextid ) {
252 $oldid = $nextid;
253 } else {
254 $wgOut->redirect( $this->mTitle->getFullURL( 'redirect=no' ) );
255 }
256 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
257 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
258 if ( $previd ) {
259 $oldid = $previd;
260 } else {
261 # TODO
262 }
263 }
264 $lastid = $oldid;
265 }
266 return @$oldid; # "@" to be able to return "unset" without PHP complaining
267 }
268
269
270 /**
271 * Load the revision (including cur_text) into this object
272 */
273 function loadContent( $noredir = false ) {
274 global $wgOut, $wgRequest;
275
276 if ( $this->mContentLoaded ) return;
277
278 # Query variables :P
279 $oldid = $this->getOldID();
280 $redirect = $wgRequest->getVal( 'redirect' );
281
282 $fname = 'Article::loadContent';
283
284 # Pre-fill content with error message so that if something
285 # fails we'll have something telling us what we intended.
286
287 $t = $this->mTitle->getPrefixedText();
288
289 $noredir = $noredir || ($wgRequest->getVal( 'redirect' ) == 'no')
290 || $wgRequest->getCheck( 'rdfrom' );
291 $this->mOldId = $oldid;
292 $this->fetchContent( $oldid, $noredir, true );
293 }
294
295
296 /**
297 * Fetch a page record with the given conditions
298 * @param Database $dbr
299 * @param array $conditions
300 * @access private
301 */
302 function pageData( &$dbr, $conditions ) {
303 $fields = array(
304 'page_id',
305 'page_namespace',
306 'page_title',
307 'page_restrictions',
308 'page_counter',
309 'page_is_redirect',
310 'page_is_new',
311 'page_random',
312 'page_touched',
313 'page_latest',
314 'page_len' ) ;
315 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
316 $row = $dbr->selectRow( 'page',
317 $fields,
318 $conditions,
319 'Article::pageData' );
320 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
321 return $row ;
322 }
323
324 function pageDataFromTitle( &$dbr, $title ) {
325 return $this->pageData( $dbr, array(
326 'page_namespace' => $title->getNamespace(),
327 'page_title' => $title->getDBkey() ) );
328 }
329
330 function pageDataFromId( &$dbr, $id ) {
331 return $this->pageData( $dbr, array(
332 'page_id' => intval( $id ) ) );
333 }
334
335 /**
336 * Set the general counter, title etc data loaded from
337 * some source.
338 *
339 * @param object $data
340 * @access private
341 */
342 function loadPageData( $data ) {
343 $this->mTitle->loadRestrictions( $data->page_restrictions );
344 $this->mTitle->mRestrictionsLoaded = true;
345
346 $this->mCounter = $data->page_counter;
347 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
348 $this->mIsRedirect = $data->page_is_redirect;
349 $this->mLatest = $data->page_latest;
350
351 $this->mDataLoaded = true;
352 }
353
354 /**
355 * Get text of an article from database
356 * @param int $oldid 0 for whatever the latest revision is
357 * @param bool $noredir Set to false to follow redirects
358 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
359 * @return string
360 */
361 function fetchContent( $oldid = 0, $noredir = true, $globalTitle = false ) {
362 if ( $this->mContentLoaded ) {
363 return $this->mContent;
364 }
365
366 $dbr =& $this->getDB();
367 $fname = 'Article::fetchContent';
368
369 # Pre-fill content with error message so that if something
370 # fails we'll have something telling us what we intended.
371 $t = $this->mTitle->getPrefixedText();
372 if( $oldid ) {
373 $t .= ',oldid='.$oldid;
374 }
375 if( isset( $redirect ) ) {
376 $redirect = ($redirect == 'no') ? 'no' : 'yes';
377 $t .= ',redirect='.$redirect;
378 }
379 $this->mContent = wfMsg( 'missingarticle', $t );
380
381 if( $oldid ) {
382 $revision = Revision::newFromId( $oldid );
383 if( is_null( $revision ) ) {
384 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
385 return false;
386 }
387 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
388 if( !$data ) {
389 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
390 return false;
391 }
392 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
393 $this->loadPageData( $data );
394 } else {
395 if( !$this->mDataLoaded ) {
396 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
397 if( !$data ) {
398 wfDebug( "$fname failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
399 return false;
400 }
401 $this->loadPageData( $data );
402 }
403 $revision = Revision::newFromId( $this->mLatest );
404 if( is_null( $revision ) ) {
405 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
406 return false;
407 }
408 }
409
410 # If we got a redirect, follow it (unless we've been told
411 # not to by either the function parameter or the query
412 if ( !$oldid && !$noredir ) {
413 $rt = Title::newFromRedirect( $revision->getText() );
414 # process if title object is valid and not special:userlogout
415 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL && $rt->getText() == 'Userlogout' ) ) {
416 # Gotta hand redirects to special pages differently:
417 # Fill the HTTP response "Location" header and ignore
418 # the rest of the page we're on.
419 global $wgDisableHardRedirects;
420 if( $globalTitle && !$wgDisableHardRedirects ) {
421 global $wgOut;
422 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
423 $source = $this->mTitle->getFullURL( 'redirect=no' );
424 $wgOut->redirect( $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ) ) ;
425 return false;
426 }
427 if ( $rt->getNamespace() == NS_SPECIAL ) {
428 $wgOut->redirect( $rt->getFullURL() );
429 return false;
430 }
431 }
432 if( $rt->getInterwiki() == '' ) {
433 $redirData = $this->pageDataFromTitle( $dbr, $rt );
434 if( $redirData ) {
435 $redirRev = Revision::newFromId( $redirData->page_latest );
436 if( !is_null( $redirRev ) ) {
437 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
438 $this->mTitle = $rt;
439 $data = $redirData;
440 $this->loadPageData( $data );
441 $revision = $redirRev;
442 }
443 }
444 }
445 }
446 }
447
448 # if the title's different from expected, update...
449 if( $globalTitle ) {
450 global $wgTitle;
451 if( !$this->mTitle->equals( $wgTitle ) ) {
452 $wgTitle = $this->mTitle;
453 }
454 }
455
456 # Back to the business at hand...
457 $this->mContent = $revision->getText();
458
459 $this->mUser = $revision->getUser();
460 $this->mUserText = $revision->getUserText();
461 $this->mComment = $revision->getComment();
462 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
463
464 $this->mRevIdFetched = $revision->getID();
465 $this->mContentLoaded = true;
466 $this->mRevision =& $revision;
467
468 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
469
470 return $this->mContent;
471 }
472
473 /**
474 * Gets the article text without using so many damn globals
475 * Returns false on error
476 *
477 * @param integer $oldid
478 */
479 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
480 return $this->fetchContent( $oldid, $noredir, false );
481 }
482
483 /**
484 * Read/write accessor to select FOR UPDATE
485 */
486 function forUpdate( $x = NULL ) {
487 return wfSetVar( $this->mForUpdate, $x );
488 }
489
490 /**
491 * Get the database which should be used for reads
492 */
493 function &getDB() {
494 $ret =& wfGetDB( DB_MASTER );
495 return $ret;
496 #if ( $this->mForUpdate ) {
497 $ret =& wfGetDB( DB_MASTER );
498 #} else {
499 # $ret =& wfGetDB( DB_SLAVE );
500 #}
501 return $ret;
502 }
503
504 /**
505 * Get options for all SELECT statements
506 * Can pass an option array, to which the class-wide options will be appended
507 */
508 function getSelectOptions( $options = '' ) {
509 if ( $this->mForUpdate ) {
510 if ( is_array( $options ) ) {
511 $options[] = 'FOR UPDATE';
512 } else {
513 $options = 'FOR UPDATE';
514 }
515 }
516 return $options;
517 }
518
519 /**
520 * Return the Article ID
521 */
522 function getID() {
523 if( $this->mTitle ) {
524 return $this->mTitle->getArticleID();
525 } else {
526 return 0;
527 }
528 }
529
530 /**
531 * Returns true if this article exists in the database.
532 * @return bool
533 */
534 function exists() {
535 return $this->getId() != 0;
536 }
537
538 /**
539 * Get the view count for this article
540 */
541 function getCount() {
542 if ( -1 == $this->mCounter ) {
543 $id = $this->getID();
544 $dbr =& $this->getDB();
545 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
546 'Article::getCount', $this->getSelectOptions() );
547 }
548 return $this->mCounter;
549 }
550
551 /**
552 * Would the given text make this article a "good" article (i.e.,
553 * suitable for including in the article count)?
554 * @param string $text Text to analyze
555 * @return integer 1 if it can be counted else 0
556 */
557 function isCountable( $text ) {
558 global $wgUseCommaCount;
559
560 if ( NS_MAIN != $this->mTitle->getNamespace() ) { return 0; }
561 if ( $this->isRedirect( $text ) ) { return 0; }
562 $token = ($wgUseCommaCount ? ',' : '[[' );
563 if ( false === strstr( $text, $token ) ) { return 0; }
564 return 1;
565 }
566
567 /**
568 * Tests if the article text represents a redirect
569 */
570 function isRedirect( $text = false ) {
571 if ( $text === false ) {
572 $this->loadContent();
573 $titleObj = Title::newFromRedirect( $this->fetchContent() );
574 } else {
575 $titleObj = Title::newFromRedirect( $text );
576 }
577 return $titleObj !== NULL;
578 }
579
580 /**
581 * Returns true if the currently-referenced revision is the current edit
582 * to this page (and it exists).
583 * @return bool
584 */
585 function isCurrent() {
586 return $this->exists() &&
587 isset( $this->mRevision ) &&
588 $this->mRevision->isCurrent();
589 }
590
591 /**
592 * Loads everything except the text
593 * This isn't necessary for all uses, so it's only done if needed.
594 * @private
595 */
596 function loadLastEdit() {
597 global $wgOut;
598
599 if ( -1 != $this->mUser )
600 return;
601
602 # New or non-existent articles have no user information
603 $id = $this->getID();
604 if ( 0 == $id ) return;
605
606 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
607 if( !is_null( $this->mLastRevision ) ) {
608 $this->mUser = $this->mLastRevision->getUser();
609 $this->mUserText = $this->mLastRevision->getUserText();
610 $this->mTimestamp = $this->mLastRevision->getTimestamp();
611 $this->mComment = $this->mLastRevision->getComment();
612 $this->mMinorEdit = $this->mLastRevision->isMinor();
613 }
614 }
615
616 function getTimestamp() {
617 $this->loadLastEdit();
618 return wfTimestamp(TS_MW, $this->mTimestamp);
619 }
620
621 function getUser() {
622 $this->loadLastEdit();
623 return $this->mUser;
624 }
625
626 function getUserText() {
627 $this->loadLastEdit();
628 return $this->mUserText;
629 }
630
631 function getComment() {
632 $this->loadLastEdit();
633 return $this->mComment;
634 }
635
636 function getMinorEdit() {
637 $this->loadLastEdit();
638 return $this->mMinorEdit;
639 }
640
641 function getRevIdFetched() {
642 $this->loadLastEdit();
643 return $this->mRevIdFetched;
644 }
645
646 function getContributors($limit = 0, $offset = 0) {
647 $fname = 'Article::getContributors';
648
649 # XXX: this is expensive; cache this info somewhere.
650
651 $title = $this->mTitle;
652 $contribs = array();
653 $dbr =& $this->getDB();
654 $revTable = $dbr->tableName( 'revision' );
655 $userTable = $dbr->tableName( 'user' );
656 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
657 $ns = $title->getNamespace();
658 $user = $this->getUser();
659 $pageId = $this->getId();
660
661 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
662 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
663 WHERE rev_page = $pageId
664 AND rev_user != $user
665 GROUP BY rev_user, rev_user_text, user_real_name
666 ORDER BY timestamp DESC";
667
668 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
669 $sql .= ' '. $this->getSelectOptions();
670
671 $res = $dbr->query($sql, $fname);
672
673 while ( $line = $dbr->fetchObject( $res ) ) {
674 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
675 }
676
677 $dbr->freeResult($res);
678 return $contribs;
679 }
680
681 /**
682 * This is the default action of the script: just view the page of
683 * the given title.
684 */
685 function view() {
686 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgContLang;
687 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
688 global $wgParserCache, $wgUseTrackbacks;
689 $sk = $wgUser->getSkin();
690
691 $fname = 'Article::view';
692 wfProfileIn( $fname );
693 # Get variables from query string
694 $oldid = $this->getOldID();
695 $diff = $wgRequest->getVal( 'diff' );
696 $rcid = $wgRequest->getVal( 'rcid' );
697 $rdfrom = $wgRequest->getVal( 'rdfrom' );
698
699 $wgOut->setArticleFlag( true );
700 $wgOut->setRobotpolicy( 'index,follow' );
701 # If we got diff and oldid in the query, we want to see a
702 # diff page instead of the article.
703
704 if ( !is_null( $diff ) ) {
705 require_once( 'DifferenceEngine.php' );
706 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
707
708 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid );
709 // DifferenceEngine directly fetched the revision:
710 $this->mRevIdFetched = $de->mNewid;
711 $de->showDiffPage();
712
713 if( $diff == 0 ) {
714 # Run view updates for current revision only
715 $this->viewUpdates();
716 }
717 wfProfileOut( $fname );
718 return;
719 }
720
721 if ( empty( $oldid ) && $this->checkTouched() ) {
722 $wgOut->setETag($wgParserCache->getETag($this, $wgUser));
723
724 if( $wgOut->checkLastModified( $this->mTouched ) ){
725 wfProfileOut( $fname );
726 return;
727 } else if ( $this->tryFileCache() ) {
728 # tell wgOut that output is taken care of
729 $wgOut->disable();
730 $this->viewUpdates();
731 wfProfileOut( $fname );
732 return;
733 }
734 }
735 # Should the parser cache be used?
736 $pcache = $wgEnableParserCache &&
737 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
738 $this->exists() &&
739 empty( $oldid );
740 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
741
742 $outputDone = false;
743 if ( $pcache ) {
744 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
745 $outputDone = true;
746 }
747 }
748 if ( !$outputDone ) {
749 $text = $this->getContent( false ); # May change mTitle by following a redirect
750
751 # Another whitelist check in case oldid or redirects are altering the title
752 if ( !$this->mTitle->userCanRead() ) {
753 $wgOut->loginToUse();
754 $wgOut->output();
755 exit;
756 }
757
758 # We're looking at an old revision
759
760 if ( !empty( $oldid ) ) {
761 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
762 $wgOut->setRobotpolicy( 'noindex,follow' );
763 }
764 $wasRedirected = false;
765 if ( '' != $this->mRedirectedFrom ) {
766 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
767 $sk = $wgUser->getSkin();
768 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '', 'redirect=no' );
769 $s = wfMsg( 'redirectedfrom', $redir );
770 $wgOut->setSubtitle( $s );
771
772 // Check the parser cache again, for the target page
773 if( $pcache ) {
774 if( $wgOut->tryParserCache( $this, $wgUser ) ) {
775 $outputDone = true;
776 }
777 }
778 $wasRedirected = true;
779 }
780 } elseif ( !empty( $rdfrom ) ) {
781 global $wgRedirectSources;
782 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
783 $sk = $wgUser->getSkin();
784 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
785 $s = wfMsg( 'redirectedfrom', $redir );
786 $wgOut->setSubtitle( $s );
787 $wasRedirected = true;
788 }
789 }
790 }
791 if( !$outputDone ) {
792 /**
793 * @fixme: this hook doesn't work most of the time, as it doesn't
794 * trigger when the parser cache is used.
795 */
796 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
797 # wrap user css and user js in pre and don't parse
798 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
799 if (
800 $this->mTitle->getNamespace() == NS_USER &&
801 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
802 ) {
803 $wgOut->setRevisionId( $this->getRevIdFetched() );
804 $wgOut->addWikiText( wfMsg('clearyourcache'));
805 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
806 } else if ( $rt = Title::newFromRedirect( $text ) ) {
807 # Display redirect
808 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
809 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
810 if( !$wasRedirected ) {
811 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
812 }
813 $targetUrl = $rt->escapeLocalURL();
814 $titleText = htmlspecialchars( $rt->getPrefixedText() );
815 $link = $sk->makeLinkObj( $rt );
816
817 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
818 '<span class="redirectText">'.$link.'</span>' );
819
820 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
821 $catlinks = $parseout->getCategoryLinks();
822 $wgOut->addCategoryLinks($catlinks);
823 $skin = $wgUser->getSkin();
824 } else if ( $pcache ) {
825 # Display content and save to parser cache
826 $wgOut->setRevisionId( $this->getRevIdFetched() );
827 $wgOut->addPrimaryWikiText( $text, $this );
828 } else {
829 # Display content, don't attempt to save to parser cache
830
831 # Don't show section-edit links on old revisions... this way lies madness.
832 if( !$this->isCurrent() ) {
833 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
834 }
835 $wgOut->setRevisionId( $this->getRevIdFetched() );
836 $wgOut->addWikiText( $text );
837
838 if( !$this->isCurrent() ) {
839 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
840 }
841 }
842 }
843 /* title may have been set from the cache */
844 $t = $wgOut->getPageTitle();
845 if( empty( $t ) ) {
846 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
847 }
848
849 # If we have been passed an &rcid= parameter, we want to give the user a
850 # chance to mark this new article as patrolled.
851 if ( $wgUseRCPatrol
852 && !is_null($rcid)
853 && $rcid != 0
854 && $wgUser->isLoggedIn()
855 && ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
856 {
857 $wgOut->addHTML(
858 "<div class='patrollink'>" .
859 wfMsg ( 'markaspatrolledlink',
860 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
861 ) .
862 '</div>'
863 );
864 }
865
866 # Trackbacks
867 if ($wgUseTrackbacks)
868 $this->addTrackbacks();
869
870 # Add link titles as META keywords
871 $wgOut->addMetaTags() ;
872
873 $this->viewUpdates();
874 wfProfileOut( $fname );
875 }
876
877 function addTrackbacks() {
878 global $wgOut, $wgUser;
879
880 $dbr =& wfGetDB(DB_SLAVE);
881 $tbs = $dbr->select(
882 /* FROM */ 'trackbacks',
883 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
884 /* WHERE */ array('tb_page' => $this->getID())
885 );
886
887 if (!$dbr->numrows($tbs))
888 return;
889
890 $tbtext = "";
891 while ($o = $dbr->fetchObject($tbs)) {
892 $rmvtxt = "";
893 if ($wgUser->isSysop()) {
894 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
895 . $o->tb_id . "&token=" . $wgUser->editToken());
896 $rmvtxt = wfMsg('trackbackremove', $delurl);
897 }
898 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
899 $o->tb_title,
900 $o->tb_url,
901 $o->tb_ex,
902 $o->tb_name,
903 $rmvtxt);
904 }
905 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
906 }
907
908 function deletetrackback() {
909 global $wgUser, $wgRequest, $wgOut, $wgTitle;
910
911 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
912 $wgOut->addWikitext(wfMsg('sessionfailure'));
913 return;
914 }
915
916 if ((!$wgUser->isAllowed('delete'))) {
917 $wgOut->sysopRequired();
918 return;
919 }
920
921 if (wfReadOnly()) {
922 $wgOut->readOnlyPage();
923 return;
924 }
925
926 $db =& wfGetDB(DB_MASTER);
927 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
928 $wgTitle->invalidateCache();
929 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
930 }
931
932 function render() {
933 global $wgOut;
934
935 $wgOut->setArticleBodyOnly(true);
936 $this->view();
937 }
938
939 function purge() {
940 global $wgUser, $wgRequest, $wgOut, $wgUseSquid;
941
942 if ( $wgUser->isLoggedIn() || $wgRequest->wasPosted() ) {
943 // Invalidate the cache
944 $this->mTitle->invalidateCache();
945
946 if ( $wgUseSquid ) {
947 // Commit the transaction before the purge is sent
948 $dbw = wfGetDB( DB_MASTER );
949 $dbw->immediateCommit();
950
951 // Send purge
952 $update = SquidUpdate::newSimplePurge( $this->mTitle );
953 $update->doUpdate();
954 }
955 $this->view();
956 } else {
957 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
958 $action = $this->mTitle->escapeLocalURL( 'action=purge' );
959 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
960 $msg = str_replace( '$1',
961 "<form method=\"post\" action=\"$action\">\n" .
962 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
963 "</form>\n", $msg );
964
965 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
966 $wgOut->setRobotpolicy( 'noindex,nofollow' );
967 $wgOut->addHTML( $msg );
968 }
969 }
970
971 /**
972 * Insert a new empty page record for this article.
973 * This *must* be followed up by creating a revision
974 * and running $this->updateToLatest( $rev_id );
975 * or else the record will be left in a funky state.
976 * Best if all done inside a transaction.
977 *
978 * @param Database $dbw
979 * @param string $restrictions
980 * @return int The newly created page_id key
981 * @access private
982 */
983 function insertOn( &$dbw, $restrictions = '' ) {
984 $fname = 'Article::insertOn';
985 wfProfileIn( $fname );
986
987 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
988 $dbw->insert( 'page', array(
989 'page_id' => $page_id,
990 'page_namespace' => $this->mTitle->getNamespace(),
991 'page_title' => $this->mTitle->getDBkey(),
992 'page_counter' => 0,
993 'page_restrictions' => $restrictions,
994 'page_is_redirect' => 0, # Will set this shortly...
995 'page_is_new' => 1,
996 'page_random' => wfRandom(),
997 'page_touched' => $dbw->timestamp(),
998 'page_latest' => 0, # Fill this in shortly...
999 'page_len' => 0, # Fill this in shortly...
1000 ), $fname );
1001 $newid = $dbw->insertId();
1002
1003 $this->mTitle->resetArticleId( $newid );
1004
1005 wfProfileOut( $fname );
1006 return $newid;
1007 }
1008
1009 /**
1010 * Update the page record to point to a newly saved revision.
1011 *
1012 * @param Database $dbw
1013 * @param Revision $revision -- for ID number, and text used to set
1014 length and redirect status fields
1015 * @param int $lastRevision -- if given, will not overwrite the page field
1016 * when different from the currently set value.
1017 * Giving 0 indicates the new page flag should
1018 * be set on.
1019 * @return bool true on success, false on failure
1020 * @access private
1021 */
1022 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1023 $fname = 'Article::updateToRevision';
1024 wfProfileIn( $fname );
1025
1026 $conditions = array( 'page_id' => $this->getId() );
1027 if( !is_null( $lastRevision ) ) {
1028 # An extra check against threads stepping on each other
1029 $conditions['page_latest'] = $lastRevision;
1030 }
1031
1032 $text = $revision->getText();
1033 $dbw->update( 'page',
1034 array( /* SET */
1035 'page_latest' => $revision->getId(),
1036 'page_touched' => $dbw->timestamp(),
1037 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1038 'page_is_redirect' => Article::isRedirect( $text ) ? 1 : 0,
1039 'page_len' => strlen( $text ),
1040 ),
1041 $conditions,
1042 $fname );
1043
1044 wfProfileOut( $fname );
1045 return ( $dbw->affectedRows() != 0 );
1046 }
1047
1048 /**
1049 * If the given revision is newer than the currently set page_latest,
1050 * update the page record. Otherwise, do nothing.
1051 *
1052 * @param Database $dbw
1053 * @param Revision $revision
1054 */
1055 function updateIfNewerOn( &$dbw, $revision ) {
1056 $fname = 'Article::updateIfNewerOn';
1057 wfProfileIn( $fname );
1058
1059 $row = $dbw->selectRow(
1060 array( 'revision', 'page' ),
1061 array( 'rev_id', 'rev_timestamp' ),
1062 array(
1063 'page_id' => $this->getId(),
1064 'page_latest=rev_id' ),
1065 $fname );
1066 if( $row ) {
1067 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1068 wfProfileOut( $fname );
1069 return false;
1070 }
1071 $prev = $row->rev_id;
1072 } else {
1073 # No or missing previous revision; mark the page as new
1074 $prev = 0;
1075 }
1076
1077 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1078 wfProfileOut( $fname );
1079 return $ret;
1080 }
1081
1082 /**
1083 * Theoretically we could defer these whole insert and update
1084 * functions for after display, but that's taking a big leap
1085 * of faith, and we want to be able to report database
1086 * errors at some point.
1087 * @private
1088 */
1089 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1090 global $wgOut, $wgUser, $wgUseSquid;
1091
1092 $fname = 'Article::insertNewArticle';
1093 wfProfileIn( $fname );
1094
1095 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1096 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1097 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1098 wfProfileOut( $fname );
1099 return false;
1100 }
1101
1102 $this->mGoodAdjustment = $this->isCountable( $text );
1103 $this->mTotalAdjustment = 1;
1104
1105 $ns = $this->mTitle->getNamespace();
1106 $ttl = $this->mTitle->getDBkey();
1107
1108 # If this is a comment, add the summary as headline
1109 if($comment && $summary!="") {
1110 $text="== {$summary} ==\n\n".$text;
1111 }
1112 $text = $this->preSaveTransform( $text );
1113 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ? 1 : 0;
1114 $now = wfTimestampNow();
1115
1116 $dbw =& wfGetDB( DB_MASTER );
1117
1118 # Add the page record; stake our claim on this title!
1119 $newid = $this->insertOn( $dbw );
1120
1121 # Save the revision text...
1122 $revision = new Revision( array(
1123 'page' => $newid,
1124 'comment' => $summary,
1125 'minor_edit' => $isminor,
1126 'text' => $text
1127 ) );
1128 $revisionId = $revision->insertOn( $dbw );
1129
1130 $this->mTitle->resetArticleID( $newid );
1131
1132 # Update the page record with revision data
1133 $this->updateRevisionOn( $dbw, $revision, 0 );
1134
1135 Article::onArticleCreate( $this->mTitle );
1136 if(!$suppressRC) {
1137 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, 'default',
1138 '', strlen( $text ), $revisionId );
1139 }
1140
1141 if ($watchthis) {
1142 if(!$this->mTitle->userIsWatching()) $this->watch();
1143 } else {
1144 if ( $this->mTitle->userIsWatching() ) {
1145 $this->unwatch();
1146 }
1147 }
1148
1149 # The talk page isn't in the regular link tables, so we need to update manually:
1150 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
1151 $dbw->update( 'page',
1152 array( 'page_touched' => $dbw->timestamp($now) ),
1153 array( 'page_namespace' => $talkns,
1154 'page_title' => $ttl ),
1155 $fname );
1156
1157 # standard deferred updates
1158 $this->editUpdates( $text, $summary, $isminor, $now );
1159
1160 $oldid = 0; # new article
1161 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid, $revisionId );
1162
1163 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1164 $summary, $isminor,
1165 $watchthis, NULL ) );
1166 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1167 $summary, $isminor,
1168 $watchthis, NULL ) );
1169 wfProfileOut( $fname );
1170 }
1171
1172 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1173 $this->replaceSection( $section, $text, $summary, $edittime );
1174 }
1175
1176 /**
1177 * @return string Complete article text, or null if error
1178 */
1179 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1180 $fname = 'Article::replaceSection';
1181 wfProfileIn( $fname );
1182
1183 if ($section != '') {
1184 if( is_null( $edittime ) ) {
1185 $rev = Revision::newFromTitle( $this->mTitle );
1186 } else {
1187 $dbw =& wfGetDB( DB_MASTER );
1188 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1189 }
1190 if( is_null( $rev ) ) {
1191 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1192 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1193 return null;
1194 }
1195 $oldtext = $rev->getText();
1196
1197 if($section=='new') {
1198 if($summary) $subject="== {$summary} ==\n\n";
1199 $text=$oldtext."\n\n".$subject.$text;
1200 } else {
1201
1202 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1203 # comments to be stripped as well)
1204 $striparray=array();
1205 $parser=new Parser();
1206 $parser->mOutputType=OT_WIKI;
1207 $parser->mOptions = new ParserOptions();
1208 $oldtext=$parser->strip($oldtext, $striparray, true);
1209
1210 # now that we can be sure that no pseudo-sections are in the source,
1211 # split it up
1212 # Unfortunately we can't simply do a preg_replace because that might
1213 # replace the wrong section, so we have to use the section counter instead
1214 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1215 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1216 $secs[$section*2]=$text."\n\n"; // replace with edited
1217
1218 # section 0 is top (intro) section
1219 if($section!=0) {
1220
1221 # headline of old section - we need to go through this section
1222 # to determine if there are any subsections that now need to
1223 # be erased, as the mother section has been replaced with
1224 # the text of all subsections.
1225 $headline=$secs[$section*2-1];
1226 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1227 $hlevel=$matches[1];
1228
1229 # determine headline level for wikimarkup headings
1230 if(strpos($hlevel,'=')!==false) {
1231 $hlevel=strlen($hlevel);
1232 }
1233
1234 $secs[$section*2-1]=''; // erase old headline
1235 $count=$section+1;
1236 $break=false;
1237 while(!empty($secs[$count*2-1]) && !$break) {
1238
1239 $subheadline=$secs[$count*2-1];
1240 preg_match(
1241 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1242 $subhlevel=$matches[1];
1243 if(strpos($subhlevel,'=')!==false) {
1244 $subhlevel=strlen($subhlevel);
1245 }
1246 if($subhlevel > $hlevel) {
1247 // erase old subsections
1248 $secs[$count*2-1]='';
1249 $secs[$count*2]='';
1250 }
1251 if($subhlevel <= $hlevel) {
1252 $break=true;
1253 }
1254 $count++;
1255
1256 }
1257
1258 }
1259 $text=join('',$secs);
1260 # reinsert the stuff that we stripped out earlier
1261 $text=$parser->unstrip($text,$striparray);
1262 $text=$parser->unstripNoWiki($text,$striparray);
1263 }
1264
1265 }
1266 wfProfileOut( $fname );
1267 return $text;
1268 }
1269
1270 /**
1271 * Change an existing article. Puts the previous version back into the old table, updates RC
1272 * and all necessary caches, mostly via the deferred update array.
1273 *
1274 * It is possible to call this function from a command-line script, but note that you should
1275 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1276 */
1277 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1278 global $wgOut, $wgUser, $wgDBtransactions, $wgMwRedir, $wgUseSquid;
1279 global $wgPostCommitUpdateList, $wgUseFileCache;
1280
1281 $fname = 'Article::updateArticle';
1282 wfProfileIn( $fname );
1283 $good = true;
1284
1285 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1286 &$summary, &$minor,
1287 &$watchthis, &$sectionanchor ) ) ) {
1288 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1289 wfProfileOut( $fname );
1290 return false;
1291 }
1292
1293 $isminor = ( $minor && $wgUser->isLoggedIn() );
1294 if ( $this->isRedirect( $text ) ) {
1295 # Remove all content but redirect
1296 # This could be done by reconstructing the redirect from a title given by
1297 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1298 # wants to see
1299 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1300 $redir = 1;
1301 $text = $m[1] . "\n";
1302 }
1303 }
1304 else { $redir = 0; }
1305
1306 $text = $this->preSaveTransform( $text );
1307 $dbw =& wfGetDB( DB_MASTER );
1308 $now = wfTimestampNow();
1309
1310 # Update article, but only if changed.
1311
1312 # It's important that we either rollback or complete, otherwise an attacker could
1313 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1314 # could conceivably have the same effect, especially if cur is locked for long periods.
1315 if( !$wgDBtransactions ) {
1316 $userAbort = ignore_user_abort( true );
1317 }
1318
1319 $oldtext = $this->getContent( true );
1320 $oldsize = strlen( $oldtext );
1321 $newsize = strlen( $text );
1322 $lastRevision = 0;
1323 $revisionId = 0;
1324
1325 if ( 0 != strcmp( $text, $oldtext ) ) {
1326 $this->mGoodAdjustment = $this->isCountable( $text )
1327 - $this->isCountable( $oldtext );
1328 $this->mTotalAdjustment = 0;
1329 $now = wfTimestampNow();
1330
1331 $lastRevision = $dbw->selectField(
1332 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1333
1334 $revision = new Revision( array(
1335 'page' => $this->getId(),
1336 'comment' => $summary,
1337 'minor_edit' => $isminor,
1338 'text' => $text
1339 ) );
1340
1341 $dbw->immediateCommit();
1342 $dbw->begin();
1343 $revisionId = $revision->insertOn( $dbw );
1344
1345 # Update page
1346 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1347
1348 if( !$ok ) {
1349 /* Belated edit conflict! Run away!! */
1350 $good = false;
1351 $dbw->rollback();
1352 } else {
1353 # Update recentchanges and purge cache and whatnot
1354 $bot = (int)($wgUser->isBot() || $forceBot);
1355 RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1356 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1357 $revisionId );
1358 $dbw->commit();
1359
1360 // Update caches outside the main transaction
1361 Article::onArticleEdit( $this->mTitle );
1362 }
1363 }
1364
1365 if( !$wgDBtransactions ) {
1366 ignore_user_abort( $userAbort );
1367 }
1368
1369 if ( $good ) {
1370 if ($watchthis) {
1371 if (!$this->mTitle->userIsWatching()) {
1372 $dbw->immediateCommit();
1373 $dbw->begin();
1374 $this->watch();
1375 $dbw->commit();
1376 }
1377 } else {
1378 if ( $this->mTitle->userIsWatching() ) {
1379 $dbw->immediateCommit();
1380 $dbw->begin();
1381 $this->unwatch();
1382 $dbw->commit();
1383 }
1384 }
1385 # standard deferred updates
1386 $this->editUpdates( $text, $summary, $minor, $now );
1387
1388
1389 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision, $revisionId );
1390 }
1391 wfRunHooks( 'ArticleSaveComplete',
1392 array( &$this, &$wgUser, $text,
1393 $summary, $minor,
1394 $watchthis, $sectionanchor ) );
1395 wfProfileOut( $fname );
1396 return $good;
1397 }
1398
1399 /**
1400 * After we've either updated or inserted the article, update
1401 * the link tables and redirect to the new page.
1402 */
1403 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid, $newid ) {
1404 global $wgUseDumbLinkUpdate, $wgAntiLockFlags, $wgOut, $wgUser, $wgLinkCache;
1405 global $wgUseEnotif;
1406
1407 $fname = 'Article::showArticle';
1408 wfProfileIn( $fname );
1409
1410 $wgLinkCache = new LinkCache();
1411
1412 if ( !$wgUseDumbLinkUpdate ) {
1413 # Preload links to reduce lock time
1414 if ( $wgAntiLockFlags & ALF_PRELOAD_LINKS ) {
1415 $wgLinkCache->preFill( $this->mTitle );
1416 $wgLinkCache->clear();
1417 }
1418 }
1419
1420 # Parse the text and save it to the parser cache
1421 $wgOut = new OutputPage();
1422 $wgOut->setParserOptions( ParserOptions::newFromUser( $wgUser ) );
1423 $wgOut->setRevisionId( $newid );
1424 $wgOut->addPrimaryWikiText( $text, $this );
1425
1426 if ( !$wgUseDumbLinkUpdate ) {
1427 # Move the current links back to the second register
1428 $wgLinkCache->swapRegisters();
1429
1430 # Get old version of link table to allow incremental link updates
1431 # Lock this data now since it is needed for an update
1432 $wgLinkCache->forUpdate( true );
1433 $wgLinkCache->preFill( $this->mTitle );
1434
1435 # Swap this old version back into its rightful place
1436 $wgLinkCache->swapRegisters();
1437 }
1438
1439 if( $this->isRedirect( $text ) )
1440 $r = 'redirect=no';
1441 else
1442 $r = '';
1443 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1444
1445 wfProfileOut( $fname );
1446 }
1447
1448 /**
1449 * Mark this particular edit as patrolled
1450 */
1451 function markpatrolled() {
1452 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1453 $wgOut->setRobotpolicy( 'noindex,follow' );
1454
1455 if ( !$wgUseRCPatrol )
1456 {
1457 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1458 return;
1459 }
1460 if ( $wgUser->isAnon() )
1461 {
1462 $wgOut->loginToUse();
1463 return;
1464 }
1465 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1466 {
1467 $wgOut->sysopRequired();
1468 return;
1469 }
1470 $rcid = $wgRequest->getVal( 'rcid' );
1471 if ( !is_null ( $rcid ) )
1472 {
1473 RecentChange::markPatrolled( $rcid );
1474 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1475 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1476
1477 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1478 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1479 }
1480 else
1481 {
1482 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1483 }
1484 }
1485
1486 /**
1487 * Validate function
1488 */
1489 function validate() {
1490 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1491
1492 if ( !$wgUseValidation ) # Are we using article validation at all?
1493 {
1494 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1495 return ;
1496 }
1497
1498 $wgOut->setRobotpolicy( 'noindex,follow' );
1499 $revision = $wgRequest->getVal( 'revision' );
1500
1501 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1502
1503 $v = new Validation ;
1504 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1505 $t = $v->showList ( $this ) ;
1506 else if ( $wgRequest->getVal ( "mode" , "" ) == "details" )
1507 $t = $v->showDetails ( $this , $wgRequest->getVal( 'revision' ) ) ;
1508 else
1509 $t = $v->validatePageForm ( $this , $revision ) ;
1510
1511 $wgOut->addHTML ( $t ) ;
1512 }
1513
1514 /**
1515 * Add this page to $wgUser's watchlist
1516 */
1517
1518 function watch() {
1519
1520 global $wgUser, $wgOut;
1521
1522 if ( $wgUser->isAnon() ) {
1523 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1524 return;
1525 }
1526 if ( wfReadOnly() ) {
1527 $wgOut->readOnlyPage();
1528 return;
1529 }
1530
1531 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1532
1533 $wgUser->addWatch( $this->mTitle );
1534 $wgUser->saveSettings();
1535
1536 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1537
1538 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1539 $wgOut->setRobotpolicy( 'noindex,follow' );
1540
1541 $link = $this->mTitle->getPrefixedText();
1542 $text = wfMsg( 'addedwatchtext', $link );
1543 $wgOut->addWikiText( $text );
1544 }
1545
1546 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1547 }
1548
1549 /**
1550 * Stop watching a page
1551 */
1552
1553 function unwatch() {
1554
1555 global $wgUser, $wgOut;
1556
1557 if ( $wgUser->isAnon() ) {
1558 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1559 return;
1560 }
1561 if ( wfReadOnly() ) {
1562 $wgOut->readOnlyPage();
1563 return;
1564 }
1565
1566 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1567
1568 $wgUser->removeWatch( $this->mTitle );
1569 $wgUser->saveSettings();
1570
1571 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1572
1573 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1574 $wgOut->setRobotpolicy( 'noindex,follow' );
1575
1576 $link = $this->mTitle->getPrefixedText();
1577 $text = wfMsg( 'removedwatchtext', $link );
1578 $wgOut->addWikiText( $text );
1579 }
1580
1581 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1582 }
1583
1584 /**
1585 * action=protect handler
1586 */
1587 function protect() {
1588 require_once 'ProtectionForm.php';
1589 $form = new ProtectionForm( $this );
1590 $form->show();
1591 }
1592
1593 /**
1594 * action=unprotect handler (alias)
1595 */
1596 function unprotect() {
1597 $this->protect();
1598 }
1599
1600 /**
1601 * Update the article's restriction field, and leave a log entry.
1602 *
1603 * @param array $limit set of restriction keys
1604 * @param string $reason
1605 * @return bool true on success
1606 */
1607 function updateRestrictions( $limit = array(), $reason = '' ) {
1608 global $wgUser, $wgOut, $wgRequest;
1609
1610 if ( !$wgUser->isAllowed( 'protect' ) ) {
1611 return false;
1612 }
1613
1614 if( wfReadOnly() ) {
1615 return false;
1616 }
1617
1618 $id = $this->mTitle->getArticleID();
1619 if ( 0 == $id ) {
1620 return false;
1621 }
1622
1623 $flat = Article::flattenRestrictions( $limit );
1624 $protecting = ($flat != '');
1625
1626 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser,
1627 $limit, $reason ) ) ) {
1628
1629 $dbw =& wfGetDB( DB_MASTER );
1630 $dbw->update( 'page',
1631 array( /* SET */
1632 'page_touched' => $dbw->timestamp(),
1633 'page_restrictions' => $flat
1634 ), array( /* WHERE */
1635 'page_id' => $id
1636 ), 'Article::protect'
1637 );
1638
1639 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser,
1640 $limit, $reason ) );
1641
1642 $log = new LogPage( 'protect' );
1643 if( $protecting ) {
1644 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$flat]" ) );
1645 } else {
1646 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1647 }
1648 }
1649 return true;
1650 }
1651
1652 /**
1653 * Take an array of page restrictions and flatten it to a string
1654 * suitable for insertion into the page_restrictions field.
1655 * @param array $limit
1656 * @return string
1657 * @access private
1658 */
1659 function flattenRestrictions( $limit ) {
1660 if( !is_array( $limit ) ) {
1661 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1662 }
1663 $bits = array();
1664 foreach( $limit as $action => $restrictions ) {
1665 if( $restrictions != '' ) {
1666 $bits[] = "$action=$restrictions";
1667 }
1668 }
1669 return implode( ':', $bits );
1670 }
1671
1672 /*
1673 * UI entry point for page deletion
1674 */
1675 function delete() {
1676 global $wgUser, $wgOut, $wgRequest;
1677 $fname = 'Article::delete';
1678 $confirm = $wgRequest->wasPosted() &&
1679 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1680 $reason = $wgRequest->getText( 'wpReason' );
1681
1682 # This code desperately needs to be totally rewritten
1683
1684 # Check permissions
1685 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1686 $wgOut->sysopRequired();
1687 return;
1688 }
1689 if( wfReadOnly() ) {
1690 $wgOut->readOnlyPage();
1691 return;
1692 }
1693
1694 # Better double-check that it hasn't been deleted yet!
1695 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1696 if( !$this->mTitle->exists() ) {
1697 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1698 return;
1699 }
1700
1701 if( $confirm ) {
1702 $this->doDelete( $reason );
1703 return;
1704 }
1705
1706 # determine whether this page has earlier revisions
1707 # and insert a warning if it does
1708 # we select the text because it might be useful below
1709 $dbr =& $this->getDB();
1710 $ns = $this->mTitle->getNamespace();
1711 $title = $this->mTitle->getDBkey();
1712 $revisions = $dbr->select( array( 'page', 'revision' ),
1713 array( 'rev_id', 'rev_user_text' ),
1714 array(
1715 'page_namespace' => $ns,
1716 'page_title' => $title,
1717 'rev_page = page_id'
1718 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1719 );
1720
1721 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1722 $skin=$wgUser->getSkin();
1723 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1724 $wgOut->addHTML( $skin->historyLink() .'</b>');
1725 }
1726
1727 # Fetch cur_text
1728 $rev = Revision::newFromTitle( $this->mTitle );
1729
1730 # Fetch name(s) of contributors
1731 $rev_name = '';
1732 $all_same_user = true;
1733 while( $row = $dbr->fetchObject( $revisions ) ) {
1734 if( $rev_name != '' && $rev_name != $row->rev_user_text ) {
1735 $all_same_user = false;
1736 } else {
1737 $rev_name = $row->rev_user_text;
1738 }
1739 }
1740
1741 if( !is_null( $rev ) ) {
1742 # if this is a mini-text, we can paste part of it into the deletion reason
1743 $text = $rev->getText();
1744
1745 #if this is empty, an earlier revision may contain "useful" text
1746 $blanked = false;
1747 if( $text == '' ) {
1748 $prev = $rev->getPrevious();
1749 if( $prev ) {
1750 $text = $prev->getText();
1751 $blanked = true;
1752 }
1753 }
1754
1755 $length = strlen( $text );
1756
1757 # this should not happen, since it is not possible to store an empty, new
1758 # page. Let's insert a standard text in case it does, though
1759 if( $length == 0 && $reason === '' ) {
1760 $reason = wfMsgForContent( 'exblank' );
1761 }
1762
1763 if( $length < 500 && $reason === '' ) {
1764 # comment field=255, let's grep the first 150 to have some user
1765 # space left
1766 global $wgContLang;
1767 $text = $wgContLang->truncate( $text, 150, '...' );
1768
1769 # let's strip out newlines
1770 $text = preg_replace( "/[\n\r]/", '', $text );
1771
1772 if( !$blanked ) {
1773 if( !$all_same_user ) {
1774 $reason = wfMsgForContent( 'excontent', $text );
1775 } else {
1776 $reason = wfMsgForContent( 'excontentauthor', $text, $rev_name );
1777 }
1778 } else {
1779 $reason = wfMsgForContent( 'exbeforeblank', $text );
1780 }
1781 }
1782 }
1783
1784 return $this->confirmDelete( '', $reason );
1785 }
1786
1787 /**
1788 * Output deletion confirmation dialog
1789 */
1790 function confirmDelete( $par, $reason ) {
1791 global $wgOut, $wgUser;
1792
1793 wfDebug( "Article::confirmDelete\n" );
1794
1795 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1796 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1797 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1798 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1799
1800 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1801
1802 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1803 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1804 $token = htmlspecialchars( $wgUser->editToken() );
1805
1806 $wgOut->addHTML( "
1807 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1808 <table border='0'>
1809 <tr>
1810 <td align='right'>
1811 <label for='wpReason'>{$delcom}:</label>
1812 </td>
1813 <td align='left'>
1814 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1815 </td>
1816 </tr>
1817 <tr>
1818 <td>&nbsp;</td>
1819 <td>
1820 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1821 </td>
1822 </tr>
1823 </table>
1824 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1825 </form>\n" );
1826
1827 $wgOut->returnToMain( false );
1828 }
1829
1830
1831 /**
1832 * Perform a deletion and output success or failure messages
1833 */
1834 function doDelete( $reason ) {
1835 global $wgOut, $wgUser, $wgContLang;
1836 $fname = 'Article::doDelete';
1837 wfDebug( $fname."\n" );
1838
1839 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1840 if ( $this->doDeleteArticle( $reason ) ) {
1841 $deleted = $this->mTitle->getPrefixedText();
1842
1843 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1844 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1845
1846 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1847 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1848
1849 $wgOut->addWikiText( $text );
1850 $wgOut->returnToMain( false );
1851 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1852 } else {
1853 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1854 }
1855 }
1856 }
1857
1858 /**
1859 * Back-end article deletion
1860 * Deletes the article with database consistency, writes logs, purges caches
1861 * Returns success
1862 */
1863 function doDeleteArticle( $reason ) {
1864 global $wgUser, $wgUseSquid, $wgDeferredUpdateList;
1865 global $wgPostCommitUpdateList, $wgUseTrackbacks;
1866
1867 $fname = 'Article::doDeleteArticle';
1868 wfDebug( $fname."\n" );
1869
1870 $dbw =& wfGetDB( DB_MASTER );
1871 $ns = $this->mTitle->getNamespace();
1872 $t = $this->mTitle->getDBkey();
1873 $id = $this->mTitle->getArticleID();
1874
1875 if ( $t == '' || $id == 0 ) {
1876 return false;
1877 }
1878
1879 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1880 array_push( $wgDeferredUpdateList, $u );
1881
1882 $linksTo = $this->mTitle->getLinksTo();
1883
1884 # Squid purging
1885 if ( $wgUseSquid ) {
1886 $urls = array(
1887 $this->mTitle->getInternalURL(),
1888 $this->mTitle->getInternalURL( 'history' )
1889 );
1890
1891 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
1892 array_push( $wgPostCommitUpdateList, $u );
1893
1894 }
1895
1896 # Client and file cache invalidation
1897 Title::touchArray( $linksTo );
1898
1899
1900 // For now, shunt the revision data into the archive table.
1901 // Text is *not* removed from the text table; bulk storage
1902 // is left intact to avoid breaking block-compression or
1903 // immutable storage schemes.
1904 //
1905 // For backwards compatibility, note that some older archive
1906 // table entries will have ar_text and ar_flags fields still.
1907 //
1908 // In the future, we may keep revisions and mark them with
1909 // the rev_deleted field, which is reserved for this purpose.
1910 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1911 array(
1912 'ar_namespace' => 'page_namespace',
1913 'ar_title' => 'page_title',
1914 'ar_comment' => 'rev_comment',
1915 'ar_user' => 'rev_user',
1916 'ar_user_text' => 'rev_user_text',
1917 'ar_timestamp' => 'rev_timestamp',
1918 'ar_minor_edit' => 'rev_minor_edit',
1919 'ar_rev_id' => 'rev_id',
1920 'ar_text_id' => 'rev_text_id',
1921 ), array(
1922 'page_id' => $id,
1923 'page_id = rev_page'
1924 ), $fname
1925 );
1926
1927 # Now that it's safely backed up, delete it
1928 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1929 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1930
1931 if ($wgUseTrackbacks)
1932 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
1933
1934 # Clean up recentchanges entries...
1935 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1936
1937 # Finally, clean up the link tables
1938 $t = $this->mTitle->getPrefixedDBkey();
1939
1940 Article::onArticleDelete( $this->mTitle );
1941
1942 # Delete outgoing links
1943 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1944 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1945 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1946
1947 # Log the deletion
1948 $log = new LogPage( 'delete' );
1949 $log->addEntry( 'delete', $this->mTitle, $reason );
1950
1951 # Clear the cached article id so the interface doesn't act like we exist
1952 $this->mTitle->resetArticleID( 0 );
1953 $this->mTitle->mArticleID = 0;
1954 return true;
1955 }
1956
1957 /**
1958 * Revert a modification
1959 */
1960 function rollback() {
1961 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
1962 $fname = 'Article::rollback';
1963
1964 if ( ! $wgUser->isAllowed('rollback') ) {
1965 $wgOut->sysopRequired();
1966 return;
1967 }
1968 if ( wfReadOnly() ) {
1969 $wgOut->readOnlyPage( $this->getContent( true ) );
1970 return;
1971 }
1972 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1973 array( $this->mTitle->getPrefixedText(),
1974 $wgRequest->getVal( 'from' ) ) ) ) {
1975 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1976 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1977 return;
1978 }
1979 $dbw =& wfGetDB( DB_MASTER );
1980
1981 # Enhanced rollback, marks edits rc_bot=1
1982 $bot = $wgRequest->getBool( 'bot' );
1983
1984 # Replace all this user's current edits with the next one down
1985 $tt = $this->mTitle->getDBKey();
1986 $n = $this->mTitle->getNamespace();
1987
1988 # Get the last editor, lock table exclusively
1989 $dbw->begin();
1990 $current = Revision::newFromTitle( $this->mTitle );
1991 if( is_null( $current ) ) {
1992 # Something wrong... no page?
1993 $dbw->rollback();
1994 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1995 return;
1996 }
1997
1998 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1999 if( $from != $current->getUserText() ) {
2000 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2001 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2002 htmlspecialchars( $this->mTitle->getPrefixedText()),
2003 htmlspecialchars( $from ),
2004 htmlspecialchars( $current->getUserText() ) ) );
2005 if( $current->getComment() != '') {
2006 $wgOut->addHTML(
2007 wfMsg( 'editcomment',
2008 htmlspecialchars( $current->getComment() ) ) );
2009 }
2010 return;
2011 }
2012
2013 # Get the last edit not by this guy
2014 $user = intval( $current->getUser() );
2015 $user_text = $dbw->addQuotes( $current->getUserText() );
2016 $s = $dbw->selectRow( 'revision',
2017 array( 'rev_id', 'rev_timestamp' ),
2018 array(
2019 'rev_page' => $current->getPage(),
2020 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2021 ), $fname,
2022 array(
2023 'USE INDEX' => 'page_timestamp',
2024 'ORDER BY' => 'rev_timestamp DESC' )
2025 );
2026 if( $s === false ) {
2027 # Something wrong
2028 $dbw->rollback();
2029 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2030 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2031 return;
2032 }
2033
2034 $set = array();
2035 if ( $bot ) {
2036 # Mark all reverted edits as bot
2037 $set['rc_bot'] = 1;
2038 }
2039 if ( $wgUseRCPatrol ) {
2040 # Mark all reverted edits as patrolled
2041 $set['rc_patrolled'] = 1;
2042 }
2043
2044 if ( $set ) {
2045 $dbw->update( 'recentchanges', $set,
2046 array( /* WHERE */
2047 'rc_cur_id' => $current->getPage(),
2048 'rc_user_text' => $current->getUserText(),
2049 "rc_timestamp > '{$s->rev_timestamp}'",
2050 ), $fname
2051 );
2052 }
2053
2054 # Get the edit summary
2055 $target = Revision::newFromId( $s->rev_id );
2056 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2057 $newComment = $wgRequest->getText( 'summary', $newComment );
2058
2059 # Save it!
2060 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2061 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2062 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2063
2064 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2065 Article::onArticleEdit( $this->mTitle );
2066
2067 $dbw->commit();
2068 $wgOut->returnToMain( false );
2069 }
2070
2071
2072 /**
2073 * Do standard deferred updates after page view
2074 * @private
2075 */
2076 function viewUpdates() {
2077 global $wgDeferredUpdateList;
2078
2079 if ( 0 != $this->getID() ) {
2080 global $wgDisableCounters;
2081 if( !$wgDisableCounters ) {
2082 Article::incViewCount( $this->getID() );
2083 $u = new SiteStatsUpdate( 1, 0, 0 );
2084 array_push( $wgDeferredUpdateList, $u );
2085 }
2086 }
2087
2088 # Update newtalk / watchlist notification status
2089 global $wgUser;
2090 $wgUser->clearNotification( $this->mTitle );
2091 }
2092
2093 /**
2094 * Do standard deferred updates after page edit.
2095 * Every 1000th edit, prune the recent changes table.
2096 * @private
2097 * @param string $text
2098 */
2099 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
2100 global $wgDeferredUpdateList, $wgMessageCache, $wgUser;
2101
2102 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2103 wfSeedRandom();
2104 if ( 0 == mt_rand( 0, 999 ) ) {
2105 # Periodically flush old entries from the recentchanges table.
2106 global $wgRCMaxAge;
2107
2108 $dbw =& wfGetDB( DB_MASTER );
2109 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2110 $recentchanges = $dbw->tableName( 'recentchanges' );
2111 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2112 $dbw->query( $sql );
2113 }
2114 }
2115
2116 $id = $this->getID();
2117 $title = $this->mTitle->getPrefixedDBkey();
2118 $shortTitle = $this->mTitle->getDBkey();
2119
2120 if ( 0 != $id ) {
2121 $u = new LinksUpdate( $id, $title );
2122 array_push( $wgDeferredUpdateList, $u );
2123 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2124 array_push( $wgDeferredUpdateList, $u );
2125 $u = new SearchUpdate( $id, $title, $text );
2126 array_push( $wgDeferredUpdateList, $u );
2127
2128 # If this is another user's talk page, update newtalk
2129
2130 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2131 $other = User::newFromName( $shortTitle );
2132 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2133 // An anonymous user
2134 $other = new User();
2135 $other->setName( $shortTitle );
2136 }
2137 if( $other ) {
2138 $other->setNewtalk( true );
2139 }
2140 }
2141
2142 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2143 $wgMessageCache->replace( $shortTitle, $text );
2144 }
2145 }
2146 }
2147
2148 /**
2149 * @todo document this function
2150 * @private
2151 * @param string $oldid Revision ID of this article revision
2152 */
2153 function setOldSubtitle( $oldid=0 ) {
2154 global $wgLang, $wgOut, $wgUser;
2155
2156 $current = ( $oldid == $this->mLatest );
2157 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2158 $sk = $wgUser->getSkin();
2159 $lnk = $current
2160 ? wfMsg( 'currentrevisionlink' )
2161 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2162 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
2163 $nextlink = $current
2164 ? wfMsg( 'nextrevision' )
2165 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2166 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2167 $wgOut->setSubtitle( $r );
2168 }
2169
2170 /**
2171 * This function is called right before saving the wikitext,
2172 * so we can do things like signatures and links-in-context.
2173 *
2174 * @param string $text
2175 */
2176 function preSaveTransform( $text ) {
2177 global $wgParser, $wgUser;
2178 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2179 }
2180
2181 /* Caching functions */
2182
2183 /**
2184 * checkLastModified returns true if it has taken care of all
2185 * output to the client that is necessary for this request.
2186 * (that is, it has sent a cached version of the page)
2187 */
2188 function tryFileCache() {
2189 static $called = false;
2190 if( $called ) {
2191 wfDebug( " tryFileCache() -- called twice!?\n" );
2192 return;
2193 }
2194 $called = true;
2195 if($this->isFileCacheable()) {
2196 $touched = $this->mTouched;
2197 $cache = new CacheManager( $this->mTitle );
2198 if($cache->isFileCacheGood( $touched )) {
2199 global $wgOut;
2200 wfDebug( " tryFileCache() - about to load\n" );
2201 $cache->loadFromFileCache();
2202 return true;
2203 } else {
2204 wfDebug( " tryFileCache() - starting buffer\n" );
2205 ob_start( array(&$cache, 'saveToFileCache' ) );
2206 }
2207 } else {
2208 wfDebug( " tryFileCache() - not cacheable\n" );
2209 }
2210 }
2211
2212 /**
2213 * Check if the page can be cached
2214 * @return bool
2215 */
2216 function isFileCacheable() {
2217 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2218 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2219
2220 return $wgUseFileCache
2221 and (!$wgShowIPinHeader)
2222 and ($this->getID() != 0)
2223 and ($wgUser->isAnon())
2224 and (!$wgUser->getNewtalk())
2225 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2226 and (empty( $action ) || $action == 'view')
2227 and (!isset($oldid))
2228 and (!isset($diff))
2229 and (!isset($redirect))
2230 and (!isset($printable))
2231 and (!$this->mRedirectedFrom);
2232 }
2233
2234 /**
2235 * Loads cur_touched and returns a value indicating if it should be used
2236 *
2237 */
2238 function checkTouched() {
2239 $fname = 'Article::checkTouched';
2240 if( !$this->mDataLoaded ) {
2241 $dbr =& $this->getDB();
2242 $data = $this->pageDataFromId( $dbr, $this->getId() );
2243 if( $data ) {
2244 $this->loadPageData( $data );
2245 }
2246 }
2247 return !$this->mIsRedirect;
2248 }
2249
2250 /**
2251 * Edit an article without doing all that other stuff
2252 * The article must already exist; link tables etc
2253 * are not updated, caches are not flushed.
2254 *
2255 * @param string $text text submitted
2256 * @param string $comment comment submitted
2257 * @param bool $minor whereas it's a minor modification
2258 */
2259 function quickEdit( $text, $comment = '', $minor = 0 ) {
2260 $fname = 'Article::quickEdit';
2261 wfProfileIn( $fname );
2262
2263 $dbw =& wfGetDB( DB_MASTER );
2264 $dbw->begin();
2265 $revision = new Revision( array(
2266 'page' => $this->getId(),
2267 'text' => $text,
2268 'comment' => $comment,
2269 'minor_edit' => $minor ? 1 : 0,
2270 ) );
2271 $revisionId = $revision->insertOn( $dbw );
2272 $this->updateRevisionOn( $dbw, $revision );
2273 $dbw->commit();
2274
2275 wfProfileOut( $fname );
2276 }
2277
2278 /**
2279 * Used to increment the view counter
2280 *
2281 * @static
2282 * @param integer $id article id
2283 */
2284 function incViewCount( $id ) {
2285 $id = intval( $id );
2286 global $wgHitcounterUpdateFreq;
2287
2288 $dbw =& wfGetDB( DB_MASTER );
2289 $pageTable = $dbw->tableName( 'page' );
2290 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2291 $acchitsTable = $dbw->tableName( 'acchits' );
2292
2293 if( $wgHitcounterUpdateFreq <= 1 ){ //
2294 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2295 return;
2296 }
2297
2298 # Not important enough to warrant an error page in case of failure
2299 $oldignore = $dbw->ignoreErrors( true );
2300
2301 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2302
2303 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2304 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2305 # Most of the time (or on SQL errors), skip row count check
2306 $dbw->ignoreErrors( $oldignore );
2307 return;
2308 }
2309
2310 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2311 $row = $dbw->fetchObject( $res );
2312 $rown = intval( $row->n );
2313 if( $rown >= $wgHitcounterUpdateFreq ){
2314 wfProfileIn( 'Article::incViewCount-collect' );
2315 $old_user_abort = ignore_user_abort( true );
2316
2317 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2318 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2319 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2320 'GROUP BY hc_id');
2321 $dbw->query("DELETE FROM $hitcounterTable");
2322 $dbw->query('UNLOCK TABLES');
2323 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2324 'WHERE page_id = hc_id');
2325 $dbw->query("DROP TABLE $acchitsTable");
2326
2327 ignore_user_abort( $old_user_abort );
2328 wfProfileOut( 'Article::incViewCount-collect' );
2329 }
2330 $dbw->ignoreErrors( $oldignore );
2331 }
2332
2333 /**#@+
2334 * The onArticle*() functions are supposed to be a kind of hooks
2335 * which should be called whenever any of the specified actions
2336 * are done.
2337 *
2338 * This is a good place to put code to clear caches, for instance.
2339 *
2340 * This is called on page move and undelete, as well as edit
2341 * @static
2342 * @param $title_obj a title object
2343 */
2344
2345 function onArticleCreate($title_obj) {
2346 global $wgUseSquid, $wgPostCommitUpdateList;
2347
2348 $title_obj->touchLinks();
2349 $titles = $title_obj->getLinksTo();
2350
2351 # Purge squid
2352 if ( $wgUseSquid ) {
2353 $urls = $title_obj->getSquidURLs();
2354 foreach ( $titles as $linkTitle ) {
2355 $urls[] = $linkTitle->getInternalURL();
2356 }
2357 $u = new SquidUpdate( $urls );
2358 array_push( $wgPostCommitUpdateList, $u );
2359 }
2360 }
2361
2362 function onArticleDelete( $title ) {
2363 global $wgMessageCache;
2364
2365 $title->touchLinks();
2366
2367 if( $title->getNamespace() == NS_MEDIAWIKI) {
2368 $wgMessageCache->replace( $title->getDBkey(), false );
2369 }
2370 }
2371
2372 /**
2373 * Purge caches on page update etc
2374 */
2375 function onArticleEdit( $title ) {
2376 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2377
2378 $urls = array();
2379
2380 // Template namespace? Purge all articles linking here.
2381 // FIXME: When a templatelinks table arrives, use it for all includes.
2382 if ( $title->getNamespace() == NS_TEMPLATE) {
2383 $titles = $title->getLinksTo();
2384 Title::touchArray( $titles );
2385 if ( $wgUseSquid ) {
2386 foreach ( $titles as $link ) {
2387 $urls[] = $link->getInternalURL();
2388 }
2389 }
2390 }
2391
2392 # Squid updates
2393 if ( $wgUseSquid ) {
2394 $urls = array_merge( $urls, $title->getSquidURLs() );
2395 $u = new SquidUpdate( $urls );
2396 array_push( $wgPostCommitUpdateList, $u );
2397 }
2398
2399 # File cache
2400 if ( $wgUseFileCache ) {
2401 $cm = new CacheManager( $title );
2402 @unlink( $cm->fileCacheName() );
2403 }
2404 }
2405
2406 /**#@-*/
2407
2408 /**
2409 * Info about this page
2410 * Called for ?action=info when $wgAllowPageInfo is on.
2411 *
2412 * @access public
2413 */
2414 function info() {
2415 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2416 $fname = 'Article::info';
2417
2418 if ( !$wgAllowPageInfo ) {
2419 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2420 return;
2421 }
2422
2423 $page = $this->mTitle->getSubjectPage();
2424
2425 $wgOut->setPagetitle( $page->getPrefixedText() );
2426 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2427
2428 # first, see if the page exists at all.
2429 $exists = $page->getArticleId() != 0;
2430 if( !$exists ) {
2431 $wgOut->addHTML( wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2432 } else {
2433 $dbr =& $this->getDB( DB_SLAVE );
2434 $wl_clause = array(
2435 'wl_title' => $page->getDBkey(),
2436 'wl_namespace' => $page->getNamespace() );
2437 $numwatchers = $dbr->selectField(
2438 'watchlist',
2439 'COUNT(*)',
2440 $wl_clause,
2441 $fname,
2442 $this->getSelectOptions() );
2443
2444 $pageInfo = $this->pageCountInfo( $page );
2445 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2446
2447 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2448 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2449 if( $talkInfo ) {
2450 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2451 }
2452 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2453 if( $talkInfo ) {
2454 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2455 }
2456 $wgOut->addHTML( '</ul>' );
2457
2458 }
2459 }
2460
2461 /**
2462 * Return the total number of edits and number of unique editors
2463 * on a given page. If page does not exist, returns false.
2464 *
2465 * @param Title $title
2466 * @return array
2467 * @access private
2468 */
2469 function pageCountInfo( $title ) {
2470 $id = $title->getArticleId();
2471 if( $id == 0 ) {
2472 return false;
2473 }
2474
2475 $dbr =& $this->getDB( DB_SLAVE );
2476
2477 $rev_clause = array( 'rev_page' => $id );
2478 $fname = 'Article::pageCountInfo';
2479
2480 $edits = $dbr->selectField(
2481 'revision',
2482 'COUNT(rev_page)',
2483 $rev_clause,
2484 $fname,
2485 $this->getSelectOptions() );
2486
2487 $authors = $dbr->selectField(
2488 'revision',
2489 'COUNT(DISTINCT rev_user_text)',
2490 $rev_clause,
2491 $fname,
2492 $this->getSelectOptions() );
2493
2494 return array( 'edits' => $edits, 'authors' => $authors );
2495 }
2496
2497 /**
2498 * Return a list of templates used by this article.
2499 * Uses the links table to find the templates
2500 *
2501 * @return array
2502 */
2503 function getUsedTemplates() {
2504 $result = array();
2505 $id = $this->mTitle->getArticleID();
2506
2507 $db =& wfGetDB( DB_SLAVE );
2508 $res = $db->select( array( 'pagelinks' ),
2509 array( 'pl_title' ),
2510 array(
2511 'pl_from' => $id,
2512 'pl_namespace' => NS_TEMPLATE ),
2513 'Article:getUsedTemplates' );
2514 if ( false !== $res ) {
2515 if ( $db->numRows( $res ) ) {
2516 while ( $row = $db->fetchObject( $res ) ) {
2517 $result[] = $row->pl_title;
2518 }
2519 }
2520 }
2521 $db->freeResult( $res );
2522 return $result;
2523 }
2524 }
2525
2526 ?>